﻿/**
 * 支付方式
 */
var pageSize = 10;
var pageNo = 1;
var index = 1;
var nameStust = 0;
var changenameStust = 0;
var info = '';
var changeNameReg = "";
// 用于校验检查室信息以及科室信息是否为空
var checkDeptArr = [];
var roomCheckArr = [];
// 接收所有所属科室信息与所属检查室信息及ID
var departmentArr = [];
var checkroomsArr = [];

$(function () {
    // 页面一加载，则获取所有科室以及检查室信息，方便显示正确数据
    getDeptInfo();
    getCheckRoomInfo();

    signsy();//初始化加载列表信息
    /*
     *点击取消清空列表
     */
    $("#queryMenu").click(function () {
        signsy();
    });
    $("#cancle").click(function () {
        $("#addModelPayModeName").val("");
        $("#changeModelPayModeName").val("");
        document.getElementById('addModelPayMOdeIco').value = '';

        $('.add-name-err').removeClass('hide').find("em").text('');
        $('.add-name-err').find("i").removeAttr('class', 'icon-ok');
        $('.add-name-err').find("i").removeAttr('class', 'icon-warn');
    });
    // 修改提交
    $("#submitMenu_update").click(function () {
        var deptArr = [];
        var roomArr = [];
        // 获取选择的科室以及检查室
        $.each($("input:checkbox[name='department']:checked"), function (index) {
            deptArr.push($(this).val());
        });
        $.each($("input:checkbox[name='checkroom']:checked"), function (idx) {
            roomArr.push($(this).val());
        });
        // 再次必填校验
        // 客户端名称必填校验
        if (!($("#changeModelClientName").val().trim())) {
            $('.change-name-err').removeClass('hide').find("em").text('客户端名称不能为空');
            $('.change-name-err').find("i").attr('class', 'icon-warn').css("color", "#ea5d5f");
            return
        } else {
            $('.change-name-err').addClass("hide");
        }
        // 科室必填校验
        if (!deptArr.length) {
            $('.department-err').removeClass('hide').find("em").text('请选择科室');
            $('.department-err').find("i").attr('class', 'icon-warn').css("color", "#ea5d5f");
            return false;
        }
        // 检查室必填校验
        if (!roomArr.length) {
            $('.checkroom-err').removeClass('hide').find("em").text('请选择检查室');
            $('.checkroom-err').find("i").attr('class', 'icon-warn').css("color", "#ea5d5f");
            return false
        }
        // 获取所有输入框中的文本框
        var oInput = $("#myModal_update input[userType='text']");
        // 客户端名称
        var clientName = oInput.eq(0).val(),
            // 客户端类型
            clientType = oInput.eq(1).attr("data-client"),

            // 所属科室ID的数组
            deptIdArr = deptArr,
            // 所属科室ID拼接字符串
            clientByIdStr = deptIdArr.join(","),
            //所属检查室ID数组
            checkIdArr = roomArr,
            // 所属检查室ID拼接字符串
            checkByIdStr = checkIdArr.join(","),
            clientId = $("#submitMenu_update").attr("data-userId");
        $.ajax({
            url: "/sys/client/enter",
            type: 'post',
            data: {
                clientId: clientId,
                clientName: clientName,
                clientType: clientType,
                clientByDeptId: clientByIdStr,
                clientByCheckId: checkByIdStr
            },
            success: function (data) {
                if (data.code == 1 && data.data != "") {
                    $("#myModal_update").modal("hide");
                    signsy();
                }
            },
            error: function (error) {
                console.log(error);
            }
        });
    });
    // 检查室

    /*
    * 新增的时候初始化模态框
    * */

    /*
    * 修改的时候支付方式名称的唯一性的验证
    * */

    // 获取所有科室信息
    function getDeptInfo() {
        $.ajax({
            // url: "data/departmentManagement2.json",
            url: "/sys/dept/info",
            type: "get",
            data: {},
            async: false,
            success: function (data) {
                var nohtml = "";
                if (data.code == 1 && data.msg != null) {
                    departmentArr = [];
                    for (var i = 0; i < data.data.length; i++) {
                        // 获取所有的科室ID以及名称
                        departmentArr.push("{'departmentId':'" + data.data[i].departmentId + "','departmentName':'" + data.data[i].departmentName + "'}");
                        nohtml += "<label class=\"label\"><input class=\"client\" " +
                            "userType=\"checkbox\" name=\"department\" value=" + data.data[i].departmentId + "  />" + data.data[i].departmentName + "</label>"
                    }
                } else {
                    nohtml += "<tr><td colspan='6'>数据为空！！</td></tr>";
                }
                $("#editDepartment").html(nohtml);
            },
            error: function (error) {
                alert("请求超时!");
            }
        })
    }

    // 获取所有检查室信息
    function getCheckRoomInfo() {
        $.ajax({
            // url: "data/checkroomManagement2.json",
            url: "/sys/checkRoom/info",
            type: "get",
            data: {},
            async: false,
            success: function (data) {
                var nohtml = "";
                if (data.code == 1 && data.msg != null) {
                    checkroomsArr = [];
                    for (var i = 0; i < data.data.length; i++) {
                        // 获取所有的检查室ID以及名称
                        checkroomsArr.push("{checkRoomId:'" + data.data[i].checkRoomId + "',checkRoomName:'" + data.data[i].checkRoomName + "'}")
                        nohtml += "<label class=\"label check\"><input userType=\"checkbox\" class=\"client\" name=\"checkroom\" " +
                            " value=" + data.data[i].checkRoomId + " data-userId='" + data.data[i].departmentId + "'  />" + data.data[i].checkRoomName + "</label>"
                    }
                } else {
                    nohtml += "<tr><td colspan='6'>数据为空！！</td></tr>";
                }
                $("#editCheckroom").html(nohtml);
            },
            error: function (error) {
                alert("请求超时!");
            }
        })
    }

    // 客户端名称必填校验
    $("#changeModelClientName").blur(function () {
        if (!($("#changeModelClientName").val().trim())) {
            $('.change-name-err').removeClass('hide').find("em").text('客户端名称不能为空');
            $('.change-name-err').find("i").attr('class', 'icon-warn').css("color", "#ea5d5f");
            return
        } else {
            $('.change-name-err').addClass("hide");
        }
    });


    // 查询
    function signsy() {
        //得到查询条件
        var clientName = ($("#clientName").val()).trim(),
            department = ($("#department").val()).trim(),
            checkroom = ($("#checkroom").val()).trim(),
            clientType = $("#clientType").val();
        $.ajax({
            // url : "data/clientManagement.json",
            url: "/sys/client/info",
            type: "get",
            async: false,
            dataType: "json",
            data: {
                clientName: clientName,
                clientType: clientType,
                departmentName: department,
                checkRoomName: checkroom
            },
            success: function (data) {
                // console.log(data);
                var nothtml = "<tr><th class='index'>序号</th><th class='name'>客户端名称</th><th>客户端类型</th><th>所属科室</th><th>所属检查室</th><th class='op'>操作</th></tr>";
                if (data.code == 1 && data.data.length) {
                    /*
                                        var dataArr = [];
                                        dataArr.push(data.data[0]);
                                        console.log(dataArr);
                                        for (var i = 1; i < data.data.length;i++){
                                            for (var j = 0;j<dataArr.length; j++) {
                                                if (data.data[i].clientId != dataArr.clientId) {
                                                    dataArr.push(data.data[i]);
                                                }
                                            }
                                        }
                                        console.log(dataArr);
                    */
                    for (var i = 0; i < data.data.length - 1; i++) {
                        for (var j = i + 1; j < data.data.length; j++) {
                            if (data.data[i].clientId == data.data[j].clientId) {

                                data.data.splice(j, 1);//console.log(arr[j]);
                                j--;
                            }
                        }
                    }
                    for (var i = 0; i < data.data.length; i++) {
                        nothtml += "<tr><td>" + (i + 1) + "</td><td>" + data.data[i].clientName + "</td>" +
                            "<td data-client='" + data.data[i].clientType + "'>" + transformClientType(data.data[i].clientType) + "</td><td data-userType='" + data.data[i].clientByDeptId + "'>"
                            + transformDept(data.data[i].clientByDeptId) + "</td><td data-room='" + data.data[i].clientByCheckId + "'>" + transformRoom(data.data[i].clientByCheckId) + "</td>" +
                            // "<td><a href=\"#\" data-toggle=\"modal\" data-target=\"#myModal_update\"  userId='" + data.data[i].clientId + "' " +
                            // "class=\"btn btn-sm btn-primary operation allUpdate\">修改</a></td>" +
                            "</tr>";
                    }

                    /*
                                        for(var i=0;i<dataArr.length;i++){
                                                                nothtml+="<tr><td>"+(i+1)+"</td><td>"+dataArr[i].clientName+"</td>" +
                                                                    "<td data-client='"+dataArr[i].clientType+"'>"+transformClientType(dataArr[i].clientType)+"</td><td data-userType='"+dataArr[i].clientByDeptId+"'>"
                                                                    +transformDept(dataArr[i].clientByDeptId)+"</td><td data-room='"+dataArr[i].clientByCheckId+"'>"+transformRoom(dataArr[i].clientByCheckId)+"</td>"+
                                                                    "<td><a href=\"#\" data-toggle=\"modal\" data-target=\"#myModal_update\"  userId='"+dataArr[i].clientId+"' " +
                                                                    "class=\"btn btn-sm btn-primary operation allUpdate\">修改</a></td></tr>";
                                                            }
                    */
                    $("#TeamSignedUser").html(nothtml);		//生成到待处理DIV模块展示
                    // 点击修改
                    $(".allUpdate").click(function () {
                        // 每次打开都清空一次
                        $('.change-name-err').removeClass('hide').find("em").text('');
                        $('.change-name-err').find("i").removeAttr('class', 'icon-ok');
                        $('.change-name-err').find("i").removeAttr('class', 'icon-warn');
                        // 科室
                        $('.department-err').removeClass('hide').find("em").text('');
                        $('.department-err').find("i").removeAttr('class', 'icon-ok');
                        $('.department-err').find("i").removeAttr('class', 'icon-warn');
                        // 检查室
                        $('.checkroom-err').removeClass('hide').find("em").text('');
                        $('.checkroom-err').find("i").removeAttr('class', 'icon-ok');
                        $('.checkroom-err').find("i").removeAttr('class', 'icon-warn');
                        //根据id进行待修改内容查询 并展示
                        $("#submitMenu_update").attr("data-userId", $(this).attr("id"));//给提交按钮提供当前修改信息行的数据库主键id

                        getDeptInfo();
                        getCheckRoomInfo();
                        //点击修改信息,模态框显示当前所需要修改的信息
                        var tag = $(this).closest('tr').find('td');
                        // 去掉修改列--不成功
                        var modal = $("#myModal_update");  //当前模态框
                        var modalTag = modal.find('.form-control');
                        // 获取原有的所属科室信息
                        var departmentArr = [];
                        // 获取原有的所属检查室
                        var checkroomArr = [];
                        // 获取所有所属科室的结点
                        var targetDepartmentArr = $("input:checkbox[name='department']");
                        // 获取所有所属检查室结点
                        var targetCheckRoomArr = $("input:checkbox[name='checkroom']");
                        for (var i = 0; i < tag.length; i++) {
                            //  将所有科室信息ID信息放入数组中
                            if (i == 3) {
                                // 将所有所属科室信息放入数组中
                                departmentArr = tag.eq(i).attr("data-userType").split(",");
                            }
                            // 获取所有的检查室ID
                            if (i == 4) {
                                checkroomArr = tag.eq(i).attr("data-room").split(",");
                            }
                            // 将客户端类型的数字绑定到自定义属性中
                            if (i == 2) {
                                modalTag.eq(1).attr("data-client", tag.eq(i).attr("data-client"))
                            }
                            // 将数据显示到文本框中
                            if (i < 3)
                                modalTag.eq(i).val(tag.eq(i + 1).text());
                        }
                        // 绑定已有的科室数据到CheckBox
                        for (var i = 0; i < departmentArr.length; i++) {
                            for (var j = 0; j < targetDepartmentArr.length; j++) {
                                if (departmentArr[i] == targetDepartmentArr.eq(j).val()) {
                                    targetDepartmentArr.eq(j).attr("checked", true);
                                }
                            }
                        }
                        // 绑定已有的检查室数据到CheckBox
                        for (var i = 0; i < checkroomArr.length; i++) {
                            for (var k = 0; k < targetCheckRoomArr.length; k++) {

                                if (checkroomArr[i] == targetCheckRoomArr.eq(k).val()) {
                                    targetCheckRoomArr.eq(k).attr("checked", true);
                                }
                            }
                        }
                        // 点击科室显示相应的检查室
                        /*
                                                $("input:checkbox[name='department']").blur(function () {
                                                    var _this = $(this);
                                                    $.each($("input:checkbox[name='checkroom']"),function (index) {
                                                        if (($(this).attr("data-userId") == _this.val()) && (_this.attr("checked"))){
                                                            console.log("点击了科室：");
                                                            console.log($(this).attr("data-userId"));
                                                        }
                                                    });
                                                    // 显示选中科室下所有的检查室
                                                    showCheckRoom();
                                                });
                        */

                        $("input:checkbox[name='department']").click(function () {
                            var _this = $(this);
                            isCheckDept();
                            $.each($("input:checkbox[name='checkroom']"), function (index) {
                                $(this).css("display", "none").parent("label").css("display", "none");
                                // 当点击checkbox的时候（也就是用户自己选的时候），
                                // 如果取消了科室选项，n那么也取消其下相应的检查室的勾选
                                if (($(this).attr("data-userId") == _this.val()) && (!_this.is("checked"))) {
                                    $(this).prop("checked", false);
                                }
                            });
                            // 显示选中科室下所有的检查室
                            showCheckRoom();
                            isCheckRoom();
                        });
                        // 选择检查室做是否选择判断处理
                        $("input:checkbox[name='checkroom']").click(function () {
                            isCheckRoom();
                        });
                        // 显示选中科室下所有的检查室
                        showCheckRoom();

                    });
                    //赋值

                } else {
                    nothtml += "<tr><td colspan='6'>数据为空！！</td></tr>";
                    $("#TeamSignedUser").html(nothtml);
                    $("#total").html(0);
                    $("#current").html(0);
                }
            },
            error: function (error) {
                alert("请求超时!");
            }
        });
    }

    // 客户端类型转换 -- 将客户端类型由0 1 2 转换为文字描述
    function transformClientType(type) {
        var typeName = {0: "呼号客户端", 1: "显示客户端", 2: "打印客户端"};
        return typeName[type];
    }

    // 点击科室出现相应的检查室
    function showCheckRoom() {
        $.each($("input:checkbox[name='department']:checked"), function (idx) {
            var tempVal = $(this);
            $.each($("input:checkbox[name='checkroom']"), function (index) {
                if (tempVal.val() == $(this).attr("data-userId")) {
                    $(this).css("display", "inline-block").parent("label").css("display", "inline-block");
                }
            });
        });
    }

    //    将科室ID字符串转换成科室名
    function transformDept(deptIdStr) {
        var departmentStr = [];
        deptIdStr = deptIdStr.split(",");
        for (var i = 0; i < deptIdStr.length; i++) {
            for (var j = 0; j < departmentArr.length; j++) {
                var target = eval('(' + departmentArr[j] + ')');
                if (target.departmentId == deptIdStr[i]) {
                    departmentStr.push(target.departmentName);
                }
            }
        }

        return departmentStr.join(",");
    }

    //    将检查室ID字符串转换成检查室
    function transformRoom(roomIdStr) {
        var roomStr = [];
        roomIdStr = roomIdStr.split(",");
        for (var i = 0; i < roomIdStr.length; i++) {
            for (var j = 0; j < checkroomsArr.length; j++) {
                var target = eval('(' + checkroomsArr[j] + ')');
                if (target.checkRoomId == roomIdStr[i]) {
                    roomStr.push(target.checkRoomName);
                }
            }
        }

        return roomStr.join(",");
    }

    // 科室是否有勾选内容
    function isCheckDept() {
        checkDeptArr = [];
        $.each($("input:checkbox[name='department']"), function (index) {
            if ($(this).is(":checked")) {
                checkDeptArr.push($(this).val());
            }
        });
        /*
                console.log("checkDeptArr:");
                console.log(checkDeptArr);
        */
        // 所属科室必填校验
        if (!checkDeptArr.length) {
            $('.department-err').removeClass('hide').find("em").text('请选择科室');
            $('.department-err').find("i").attr('class', 'icon-warn').css("color", "#ea5d5f");
            return false;
        } else {
            $('.department-err').addClass('hide');
            isCheckRoom();
            return true;
        }
    }

    // 检查室是否有勾选内容
    function isCheckRoom() {
        roomCheckArr = [];
        $.each($("input:checkbox[name='checkroom']"), function (index) {
            if ($(this).is(":checked")) {
                roomCheckArr.push($(this).val());
            }
        });
        /*
                console.log("roomCheckArr:");
                console.log(roomCheckArr);
        */
        // 所有检查室必填校验
        if (!roomCheckArr.length) {
            $('.checkroom-err').removeClass('hide').find("em").text('请选择检查室');
            $('.checkroom-err').find("i").attr('class', 'icon-warn').css("color", "#ea5d5f");
            return false;
        } else {
            $('.checkroom-err').addClass('hide');
            return true;
        }

    }

    /*
        // 所属科室必填校验
        if (!checkDeptArr.length ) {
            $('.department-err').removeClass('hide').find("em").text('请选择科室');
            $('.department-err').find("i").attr('class', 'icon-warn').css("color", "#ea5d5f");
        } else {
            $('.department-err').addClass('hide')
        }
        // 所有检查室必填校验
        if (!roomCheckArr.length) {
            $('.checkroom-err').removeClass('hide').find("em").text('请选择检查室');
            $('.checkroom-err').find("i").attr('class', 'icon-warn').css("color", "#ea5d5f");
        } else {
            $('.checkroom-err').addClass('hide')
        }
    */


});